/***************************************************************************
 *   Copyright (C) 2007 by gaojian   *
 *   781102@vip.sina.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "floatwin.h"
#include "htmlpart.h"
#include "clipboardpoll.h"
#include "settings.h"

#include <qlayout.h>
#include <qclipboard.h>
#include <qstring.h>
#include <qapplication.h>
#include <qdragobject.h>
#include <qtimer.h>
#include <qcursor.h>
#include <qregion.h>
#include <qregexp.h>

#include <kwin.h>
#include <netwm_def.h>
#include <khtmlview.h>
#include <kurl.h>
#include <kapp.h>

floatWin::floatWin(QWidget* parent, const char* name)
	: QWidget( parent, name,Qt::WStyle_Customize | Qt::WDestructiveClose | Qt::WX11BypassWM | Qt::WStyle_StaysOnTop | Qt::WStyle_Tool | Qt::WStyle_NoBorder )
{
resize(270,100);
KWin::setState( winId(), NET::SkipTaskbar | NET::SkipPager );//隐藏任务栏的程序图标
TranslateDialogBaseLayout = new QVBoxLayout( this, 0, 6, "floatwinLayout"); 
m_html = new htmlPart(this);
QObject::connect( m_html, SIGNAL( doubleClickEvent() ), this, SLOT( htmlPartDoubleClick() ) );
TranslateDialogBaseLayout->addWidget(m_html->view());
}


floatWin::~floatWin()
{
}

void floatWin::htmlPartDoubleClick()
{
emit fetchResult(lastText);
    qDebug("dsfsdfdsfsd");
}



/*!
    \fn floatWin::startFetchWord()
 */
void floatWin::startFetchWord()
{
	cb = QApplication::clipboard();//得到全局的剪贴簿
	mime = cb->data(QClipboard::Selection);//取出剪贴簿中选取的内容
	if(QTextDrag::canDecode(mime))//判断能否用文本解析剪贴簿中的内容
	{
		if (!QTextDrag::decode(mime, firstText))//解析到firsttext中
		{
		return;
		}
	}
	else{
	return;
		}
	timercheckCursor = new QTimer( this );//这个定时器用来检测鼠标是否在指定区域中
	connect( timercheckCursor, SIGNAL(timeout()), this, SLOT(checkCursor()) );
	poll = new ClipboardPoll( this );//建立轮询剪贴簿的类
	connect( poll, SIGNAL( clipboardChanged( bool ) ), this, SLOT( pollClip() ) );
	//把修饰键转换为编码
}

void floatWin::stopFetchWord()
{
	if(isEnabled ())
	{
		hide();
	}
	timercheckCursor->stop();
	delete timercheckCursor;
	timercheckCursor = NULL;
	delete poll;
	poll = NULL;
}

void floatWin::checkCursor()
{

    if(!reg->contains(QCursor::pos()))
	{
		hide();//如果鼠标不再区域中就隐藏窗口
		timercheckCursor->stop();//停止检测鼠标
	}
    
}

void floatWin::moveEvent ( QMoveEvent * ) 
{
reg = new QRegion(this->x()-20, this->y()-20, 310, 140);
}

/*!
    \fn floatWin::regText(QString &text);
 */
void floatWin::regText(QString &text)
{
    text=text.stripWhiteSpace ();//去掉前后空格
	text=text.lower();//都转换成小写 
	int reg = text.find( QRegExp("[{}()|~!@#$%^&*-+=|:;\"'<>,.?/]"), 0 );//在字符串中查找这些字符
	if(-1!=reg)
	{
		if(0==reg)
		{
			text=text.right( text.length()-1);
			qDebug("截取了");
			qDebug(text);
			regText(text);
		}else{
			text=text.left(reg);
			}
	}
}

void floatWin::pollClip()
{
    mime = cb->data(QClipboard::Selection);
    if ( !mime ) {
        kdWarning("No data in clipboard. This not not supposed to happen." );
        return;
    }

	if(QTextDrag::canDecode(mime))
	{
		if (QTextDrag::decode(mime, lastText))
		{	
			if(lastText.length ()>40 | lastText.startsWith("http:") | lastText.startsWith("file:"))
			{
			return;
			}else{
				regText(lastText);
				if(lastText==firstText){return;};//如果这个词已经存在剪贴簿中就返回
				//判是否需要按下修饰键，以及按键是否正确
				if(kdictsettings.b_needModifier &&  ! ( kapp->keyboardMouseState() & kdictsettings.buttonInt  ) ) return;
				QPoint pos( 10, 10 );
				pos+=QCursor::pos();
				move( pos );
				m_html->begin();
				m_html->write("");
				m_html->end();
				setWFlags(Qt::WStyle_Customize | Qt::WDestructiveClose | Qt::WX11BypassWM | Qt::WStyle_StaysOnTop | Qt::WStyle_Tool | Qt::WStyle_NoBorder);
				KWin::setState( winId(), NET::SkipTaskbar | NET::SkipPager | NET::StaysOnTop);
				show();
				setActiveWindow();
				setFocus();
				firstText=lastText;
				m_html->openURL(KURL("http://dict.cn/mini.php?q="+lastText).url());
				timercheckCursor->start( 200, FALSE ); // 200毫秒连续触发定时器
			}
		}
	}
}

#include "floatwin.moc"

